﻿using supermarket.method;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace supermarket
{
    public partial class dataManage : Form
    {
        public SqlConnection sql = new Classgetsql().getcon();
        public dataManage ()
        {
            InitializeComponent();
        }

        private void dataManage_Load ( object sender, EventArgs e )
        {

        }

        private void BtnExport_Click ( object sender, EventArgs e )
        {
            if (string.IsNullOrWhiteSpace(comboBoxTables.Text))
            {
                MessageBox.Show("请选择一个数据表！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            string tableKey = comboBoxTables.Text;
            ExportTableToCsv(tableKey);
        }
        private void ExportTableToCsv ( string tableKey )
        {
            try
            {
                string tableName;

                switch (tableKey)
                {
                    case "消费记录":
                        tableName = "[super].[dbo].[Member_Consumption_Records]";
                        break;
                    case "商品列表":
                        tableName = "[super].[dbo].[products]";
                        break;
                    case "门店列表":
                        tableName = "[super].[dbo].[shop_List]";
                        break;
                    case "门店业绩":
                        tableName = "[super].[dbo].[shop_sales]";
                        break;
                    case "员工账户":
                        tableName = "[super].[dbo].[SystemAccounts]";
                        break;
                    case "礼品列表":
                        tableName = "[super].[dbo].[Table_gift]";
                        break;
                    case "会员列表":
                        tableName = "[super].[dbo].[Table_user]";
                        break;
                    default:
                        MessageBox.Show("无效的表名！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                }

                // 使用 SaveFileDialog 选择保存路径
                using var saveFileDialog = new SaveFileDialog
                {
                    Filter = "CSV 文件 (*.csv)|*.csv",
                    FileName = $"{tableKey}.csv", // 使用简化表名作为文件名
                    Title = "保存导出文件"
                };

                if (saveFileDialog.ShowDialog() != DialogResult.OK)
                {
                    return;
                }
                if (sql.State != ConnectionState.Open)
                {
                    sql.Open();
                }
                using var command = new SqlCommand($"SELECT * FROM {tableName}", sql);
                using var reader = command.ExecuteReader();

                // 写入 CSV 文件
                var csv = new StringBuilder();

                // 写入列名
                for (int i = 0 ; i < reader.FieldCount ; i++)
                {
                    csv.Append($"\"{reader.GetName(i).Replace("\"", "\"\"")}\"");
                    if (i < reader.FieldCount - 1) csv.Append(",");
                }
                csv.AppendLine();

                // 写入数据
                while (reader.Read())
                {
                    for (int i = 0 ; i < reader.FieldCount ; i++)
                    {
                        var value = reader[i]?.ToString() ?? "";
                        csv.Append($"\"{value.Replace("\"", "\"\"")}\"");
                        if (i < reader.FieldCount - 1) csv.Append(",");
                    }
                    csv.AppendLine();
                }

                // 保存文件（使用 UTF-8 带 BOM 编码以支持中文）
                File.WriteAllText(saveFileDialog.FileName, csv.ToString(), new UTF8Encoding(true));

                MessageBox.Show("导出成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"导出失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

    }
}
